'use strict';

const Service = require('egg').Service;

class UserService extends Service {
    async login(user) {
        try {
            const result = this.app.mysql.select('user', {
                where: {
                    phone: user.phone,
                    password: user.password
                }
            })
            return {
                code: 1,
                msg: '登录成功'
            }
        } catch (e) {
            return {
                code: 0,
                msg: e.message
            }
        }
    }
    async search(phone) {
        try {
            // 去数据库查询是否有该手机号
            console.log(phone)
            const result = await this.app.mysql.select('user',{
                where: {
                    phone: phone
                }
            })
            console.log('查询结果', result, result.length)
            if (result.length !== 0) {
                return {
                    code: 0,
                    exist: true // 已存在
                }
            } else {
                return {
                    code: 1,
                    exist: false
                }
            }
        } catch (e) {
            return {
                code: 0,
                msg: e.message
            }
        }
        
    }
    async register(phone, password) {
        try {
            await this.app.mysql.insert('user', {
                phone,
                password
            })
            return {
                code: 1,
                msg: '注册成功'
            }
        } catch(e) {
            return {
                code: 0,
                msg: e.message
            }
        }
    }
}

module.exports = UserService;
